/**
 * Created by Dalyn on 2017/3/1.
 */
/*导入模块*/
import React,{Component} from 'react';
import {Link,hashHistory,browserHistory} from "react-router";
import "./Tab_title.css";
import { Menu, Icon } from 'antd';
import * as Relay from "react-relay";
const SubMenu = Menu.SubMenu;

//sadsdsds
/*默认导出组件*/
export default class Tab_menu extends React.Component {
    constructor(props){
        super(props);
        this.arr = [
            {
                text: '首页',
                link: '/syshome',
                index:'0001',
                authorityIds:['-1']
            },
            {
                text: '企业管理',
                link: '/companymanage',
                index:'1001',
                authorityIds:['1','2']
            },
            {
                text: '用户管理',
                link: '/usermanage',
                index:'2001',
                authorityIds:['5','6']
            },
            {
                text: '结算中心',
                link: '/balancecenter',
                index:'5001',
                authorityIds:[]
            },
            {
                text: '订单管理',
                link: '/indentmanage',
                index:'3001',
                authorityIds:['7','8']
            },
            {
                text: '产品管理',
                link: '/productmanage',
                index:'4001',
                authorityIds:['9','10']
            },
            {
                text: '反馈处理',
                link: '/tickling',
                index:'7001',
                authorityIds:['21','22']
            },
            {
                text: '系统设置',
                link: '/settingmanage',
                index:'6001',
                authorityIds:[]
            },
            {
                text: '数据统计',
                link: '/homepage',
                index:'8001',
                authorityIds:['20']
            }
        ];
        this.state={
            selected:true,
            current_item: '0',
            current:"",
            openKeys: [],
            current_item_product:"",
            currentMenu:"",
            authorityIds:[]
        };
        this.current_item="0";
        /*结算分级菜单*/
        this.balance_menu_item=[
            {
                key: 'settlementcenter',
                text: '企业结算',
                link: '/settlementcenter',
                authorityIds:['15','16']
            },
            {
                key: 'rechargesettlement',
                text: '账户充值',
                link: '/rechargesettlement',
                authorityIds:['18','19']
            },
            {
                key: 'loanfinance',
                text: '贷款记录',
                link: '/loanfinance',
                authorityIds:['17']
            },
            {
                key: 'invoicemanage',
                text: '发票管理',
                link: '/invoicemanage',
                authorityIds:['23']
            },
            {
                key: 'rebatemanage',
                text: '退税管理',
                link: '/rebatemanage',
                authorityIds:['24']
            }
        ];
        /*系统设置分级菜单*/
        this.sys_menu_item=[
            {
                key: 'managerlist',
                text: '人员管理',
                link: '/managerlist',
                authorityIds:['11','12']
            },
            {
                key: 'rolemanage',
                text: '角色管理',
                link: '/rolemanage',
                authorityIds:['13','14']
            }
        ];
        /*二级菜单对应的父类菜单*/
        this.subParentMenu  ={
            "/settlementcenter":"/balancecenter",
            "/rechargesettlement":"/balancecenter",
            "/loanfinance":"/balancecenter",
            "/managerlist":"/settingmanage",
            "/rolemanage":"/settingmanage",
            "/CreateCompany":"/companymanage",
            "/EditCompany":"/companymanage",
            "/ViewCompany":"/companymanage",
            "/ordertree":"/indentmanage",
            "/OrderIndex":"/indentmanage",
            "/orderdetailprint":"/indentmanage",
            "/orderdetailgms":"/indentmanage",
            "/orderdetailraw":"/indentmanage",
            "/orderdetailcloth":"/indentmanage",
            "/orderdetailyarn":"/indentmanage",
            "/ReplyDetail":"/tickling",
            "/newrole":"/settingmanage",
            "/editrole":"/settingmanage",
            "/entercensus":"/homepage",
            "/ordercensus":"/homepage",
            "/invoicemanage":"/balancecenter",
            "/rebatemanage":"/balancecenter",
        };
    }

    componentWillMount(){
        let location = browserHistory.getCurrentLocation();
        let current_item="";//
        let currentKey= "sub";
        //先查询一下是否是二级菜单
        let actionArr = null==location.hash?"":location.hash.split("/");
        let action = "";
        let action1 = "";
        if(actionArr && actionArr.length > 1 ){
            action = actionArr[1];
        }
        if("" != action){
            action1 = action;
            action = "/"+action;
            let temp = this.subParentMenu[action];//先去根据拿到数据去找一级，如果没有拿到，说明拿到的本身是一级
            if(!temp){//action是一级
                this.arr.map((item,index)=>{
                    if(action.indexOf(item.link) >=0){
                        current_item = index;
                    }
                });
                //说明选中的是一级
                this.setState({ current_item: current_item,current:action1,openKeys: []});
            }else{//拿到了temp，说明action是二级，temp是一级
                this.arr.map((item,index)=>{
                    if(temp.indexOf(item.link) >=0){
                        current_item = index;
                        currentKey = currentKey+item.index;
                    }
                });
                this.setState({ current_item: current_item,openKeys: [currentKey],current:action1});
            }
        }

        let pIds = sessionStorage.getItem('pIds');
        if (pIds != null && pIds !='' && pIds !=undefined ){
            this.setState({
                authorityIds:sessionStorage.getItem('pIds').split(",")
            });
        }

    }

    componentWillUpdate() {

    }

    leftTreeMenuClick(i){
        this.current_item = i;
        this.setState({ current_item: i});
    }
    leftTreeClick(i) {
        this.current_item = i;
        this.setState({ current_item: i});
        if(this.state.openKeys){

            this.setState(
                {
                    openKeys: [],
                    current:""
                }
            );
        }
    }
    /*Menu组件方法*/
    handleClick = (e) => {
        this.setState({ current: e.key });
    };
    /*SubMenu 展开/关闭的回调*/
    onOpenChange = (openKeys) => {
        const state = this.state;
        const latestOpenKey = openKeys.find(key => !(state.openKeys.indexOf(key) > -1));
        const latestCloseKey = state.openKeys.find(key => !(openKeys.indexOf(key) > -1));
        let nextOpenKeys = [];
        if (latestOpenKey) {
            nextOpenKeys = this.getAncestorKeys(latestOpenKey).concat(latestOpenKey);
        }
        if (latestCloseKey) {
            nextOpenKeys = this.getAncestorKeys(latestCloseKey);
        }
        this.setState({ openKeys: nextOpenKeys });
    };
    getAncestorKeys = (key) => {
        const map = {
            sub3: ['sub2'],
        };
        return map[key] || [];
    };

    /**/
    menuItemClick(index){
        this.setState({current_item_product: index})
    }

    /*结算中心子菜单*/
    menuItem_balance(){
        return this.balance_menu_item.map((item,index)=>{
            if (!this.authorityIdContain(item.authorityIds)) return;
            if(item.key == this.state.current){
                return (
                    <Menu.Item key={item.key} style={{background:"#e6f3d7",borderBottom:"1px dashed #dae8cc"}} onClick={this.menuItemClick.bind(this,index)}>
                        <Link to={item.link}  className='tab_link_a_act' style={{color:"#a0d468"}}>{item.text}</Link>
                    </Menu.Item>
                )
            }else {
                return (
                    <Menu.Item key={item.key} style={{background:"#e6f3d7",borderBottom:"1px dashed #dae8cc"}}>
                        <Link to={item.link} className='tab_link_a' style={{color:"#646464"}}>{item.text}</Link>
                    </Menu.Item>
                )
            }
        })
    }
    /*系统设置子菜单*/
    menuItem_sys(){
        return this.sys_menu_item.map((item,index)=>{
            if (!this.authorityIdContain(item.authorityIds)) return;
            if(this.state.current=='newrole' || this.state.current=='editrole'){
                this.state.current='rolemanage'
            }
            if(item.key == this.state.current){
                return (
                    <Menu.Item key={item.key} style={{background:"#e6f3d7",borderBottom:"1px dashed #dae8cc"}} onClick={this.menuItemClick.bind(this,index)}>
                        <Link to={item.link}  className='tab_link_a_act' style={{color:"#a0d468"}}>{item.text}</Link>
                    </Menu.Item>
                )
            }else {
                return (
                    <Menu.Item key={item.key} style={{background:"#e6f3d7",borderBottom:"1px dashed #dae8cc"}}>
                        <Link to={item.link} className='tab_link_a' style={{color:"#646464"}}>{item.text}</Link>
                    </Menu.Item>
                )
            }
        })
    }

    /**
     * 判断此一级菜单是否需要显示
     * @param v
     * @returns {boolean}
     */
    isShowFirstMenu(v){

        let length = v.authorityIds.length;

        if(length == 0){
            let link = v.link;
            //获取一级下的二级菜单
            let secondMenu = this.getSecondMenu(link);
            //没有二级那么返回false，不展示此一级菜单
            if (secondMenu == null || secondMenu.length == 0)
                return false;
            //如果有二级菜单,查看二级菜单是否有需要展示的菜单
            return this.checkSecondMenu(secondMenu);
        }else {
            return this.authorityIdContain(v.authorityIds);
        }
    }

    /**
     *检测是否有需要显示的二级菜单
     * @param secondMenu
     * @returns {boolean}
     */
    checkSecondMenu(secondMenu){
        let secondMenuArry = [this.balance_menu_item,this.sys_menu_item];
        for (var i = 0 ; i<secondMenuArry.length ; i++){
            let soureceSecondMenu = secondMenuArry[i];
            let  length= soureceSecondMenu.length;
            let  length02 = secondMenu.length;
            for ( var temp = 0 ; temp < length ; temp++){
                let subLink = soureceSecondMenu[temp].link;
                for ( var temp02=0 ; temp02 <length02 ; temp02++){
                    if (secondMenu[temp02] == subLink){
                       let subAuthorityIds = soureceSecondMenu[temp].authorityIds;
                        if (subAuthorityIds .length != 0){
                            if (this.authorityIdContain(subAuthorityIds))
                                return true;
                        }
                    }
                }
            }
        }
        return false;
    }
    /**
     * 获取指定一级下的二级菜单
     * @param link
     * @returns {Array}
     */
    getSecondMenu(link){
        let secondMenu=[];
        for (var p in  this.subParentMenu){
            let value = this.subParentMenu[p];
            if (value == link){
                secondMenu.push(p);
            }
        }
        return secondMenu;
    }

    /**
     * 判断此权限id是否存在此用户的权限中
     * @param authorityId
     * @returns {boolean}
     */
    authorityIdContain(authorityIds){

        let length = authorityIds.length;
        for (var i = 0 ; i <length ; i++){

            let authorityId = authorityIds[i];
            if (authorityId == '' || authorityId == null)
                continue;
            if (authorityId == '-1') return true;

            let length2 = this.state.authorityIds == null ? 0 :this.state.authorityIds.length;
            for (var j = 0 ;j< length2; j++){
                if (this.state.authorityIds[j] == authorityId){
                    return true;
                }
            }

        }

        return false;
    }
    /*二级菜单展示*/
    /*showSubMenu(key){
     if("5001" == key){
     this.menuItem_balance();
     }else if("6001" == key){
     this.menuItem_sys();
     }
     }*/
    render() {
        return (
            <div style={Style.left}  className="tab_box">
                <ul style={Style.tab_leftTree}>
                    {
                        this.arr.map((v,i) => {

                            if (!this.isShowFirstMenu(v)) return;

                            if (i == this.state.current_item) {
                                if(v.index == "5001"){
                                    return (
                                        <li onClick={this.leftTreeMenuClick.bind(this, i)} key={v.index} className='tab_leftTree_li_act'>
                                            <Menu
                                                mode="inline"
                                                openKeys={this.state.openKeys}
                                                selectedKeys={[this.state.current]}
                                                inlineIndent="24"
                                                style={{ width: 166,color:"#fff", margin:"4px 0",background:"#e6f3d7"}}
                                                onOpenChange={this.onOpenChange}
                                                onClick={this.handleClick}
                                            >
                                                <SubMenu key={"sub"+v.index} title={<span><i></i><span>{v.text}</span></span>}>
                                                    {
                                                        this.menuItem_balance()
                                                    }
                                                </SubMenu>
                                            </Menu>
                                        </li>
                                    )
                                }else if(v.index == "6001"){
                                    return (
                                        <li onClick={this.leftTreeMenuClick.bind(this, i)} key={v.index} className='tab_leftTree_li_act'>
                                            <Menu
                                                mode="inline"
                                                openKeys={this.state.openKeys}
                                                selectedKeys={[this.state.current]}
                                                inlineIndent="24"
                                                style={{ width: 166,color:"#fff", margin:"4px 0",background:"#e6f3d7"}}
                                                onOpenChange={this.onOpenChange}
                                                onClick={this.handleClick}
                                            >
                                                <SubMenu key={"sub"+v.index} title={<span><i></i><span>{v.text}</span></span>}>
                                                    {
                                                        this.menuItem_sys()
                                                    }
                                                </SubMenu>
                                            </Menu>
                                        </li>
                                    )
                                }else {
                                    return  <li onClick={this.leftTreeClick.bind(this, i)} key={"sub"+v.index} className='tab_leftTree_li_active'>
                                        <Link to={v.link}><p><i></i><span>{v.text}</span></p></Link>
                                    </li>
                                }
                            }else if(v.index == "5001" || v.index == "6001"){
                                return (
                                    <li onClick={this.leftTreeMenuClick.bind(this, i)} className='tab_leftTree_li' key={v.index}>
                                        <Menu
                                            mode="inline"
                                            openKeys={this.state.openKeys}
                                            selectedKeys={[this.state.current]}
                                            style={{ width: 164,color:"#fff", margin:"4px 0 4px 2px",background:"#a0d468"}}
                                            onOpenChange={this.onOpenChange}
                                            onClick={this.handleClick}
                                            theme="#a0d468"
                                        >
                                            <SubMenu key={"sub"+v.index} title={<span><i></i><span>{v.text}</span></span>}>

                                            </SubMenu>
                                        </Menu>
                                    </li>
                                )
                            }else {
                                return  <li onClick={this.leftTreeClick.bind(this, i)} key={"sub"+v.index} className='tab_leftTree_li'><Link to={v.link}><p><i></i><span>{v.text}</span></p></Link></li>
                            }
                        })
                    }
                </ul>
            </div>
        )
    }
}
let Style={
    left:{
        width: '166px',
        height:"900px",
        background:"#a0d468",
        position:"absolute",
        top:"0",
        left:"0",
        marginTop:63
    },
    logoBox:{
        width:"117px",
        height:"34px",
        margin:"0 auto 14px",
        padding:"15px 0 0",
    },
    logo:{
        width:"100%",
        height:"100%"
    },
    item:{
        width: '100%',
        height: '36px',
        textAlign: 'center',
        lineHeight: '36px',
        marginTop:"20px",
        position:"relative"
    },
    span:{
        fontSize:"16px",
        color:"#fff",
        paddingLeft:"18px"
    },
    item1:{
        width: '100%',
        height: '40px',
        textAlign: 'left',
        lineHeight: '40px',
        margin:"20px 0",
        paddingLeft:"32px",
        position:"relative"
    },
    i_img:{
        display:"inline-block",
        width:"20px",
        height:"20px",
        background:"url('./img/main_sp.png') no-repeat -20px -20px",
        verticalAlign:"-5px"
    }

};
